//
//  HJDFileViewController.m
//  JYHospital
//
//  Created by 胡金东 on 16/5/17.
//  Copyright © 2016年 胡金东. All rights reserved.
//

#import "HJDFileViewController.h"
#import "HJDFileViewCell.h"
#import "HJDFileModel.h"
#import "HJDDateilsViewController.h"
#import "AFNetworking.h"
#import "MJExtension.h"
#import "MJRefresh.h"


@interface HJDFileViewController ()<UITableViewDataSource,UITableViewDelegate>{
    int pageS;
    int pages;
    int n;
}

@property (nonatomic,strong) UITableView * tableView;

@property (nonatomic,strong) NSMutableArray * filesArray;

@property (nonatomic,strong)  NSString * pageCount;

@end

@implementation HJDFileViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    self.navigationItem.rightBarButtonItem = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"孕期档案表";
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:19],
       NSForegroundColorAttributeName:[UIColor getColorWithHexNumber:@"848484"]}];
     self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(backBtnClick) image:@"︿" HighImage:nil];
    
     [self setUpTableView];
    
    NSUserDefaults *phonede = [NSUserDefaults standardUserDefaults];
    NSString *phone = [phonede objectForKey:@"phonenum"];
    
    self.pageCount = @"1";
    NSString *url = @"/app/caseList.do";
    NSString *path = [Hurl stringByAppendingString:url];
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    params[@"pageSize"]= self.pageCount;
    params[@"phone"]= phone;
    
    
    [mgr POST:path parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *info =(NSDictionary *)responseObject;
        NSMutableArray *arrayR = info[@"resultMap"][@"result"];
        
        NSString *sum = info[@"resultMap"][@"count"];
        
        NSUserDefaults *defaS = [NSUserDefaults standardUserDefaults];
        [defaS setObject:sum forKey:@"countSum"];
        
        
        
        self.filesArray = (NSMutableArray *)[HJDFileModel mj_objectArrayWithKeyValuesArray:arrayR];
        
        [self.tableView reloadData];
        
      
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD showError:@"服务器升级，请稍后再试"];

    }];
    
    //添加下拉刷新控件
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewStatus)];
    //    添加上拉加载更多
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadOldStatus)];
    
    NSUserDefaults *defa = [NSUserDefaults standardUserDefaults];
    NSString *page = [defa objectForKey:@"countSum"];
    pageS = [page intValue];
//    NSLog(@"pagesS%d",pageS);
    //   总页数
    pages = (pageS/10) +1 ;
//    NSLog(@"page%d",pages);
    n = 1;

    
  
}


-(void)backBtnClick{
    [self dismissViewControllerAnimated:YES completion:nil];
}


-(void)setUpTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
//    self.filesArray = [HJDFileModel fileArray];
    [self.view addSubview:self.tableView];
}

-(void)loadNewStatus
{
    if (n <1) {
        
        
        
        self.pageCount = [NSString stringWithFormat:@"%d",n];

        NSUserDefaults *phonede = [NSUserDefaults standardUserDefaults];
        NSString *phone = [phonede objectForKey:@"phonenum"];
        
        
        NSString *url = @"/app/queryRegistrationLog.do";
        NSString *path = [Hurl stringByAppendingString:url];
        AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"pageSize"]= self.pageCount;
        params[@"phone"]= phone;
       
        [mgr POST:path parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [self.tableView.mj_header endRefreshing];
            
            NSDictionary *info =(NSDictionary *)responseObject;
            NSMutableArray *arrayR = info[@"resultMap"][@"result"];
            
            
            NSArray *statuses = (NSMutableArray *)[HJDFileModel mj_objectArrayWithKeyValuesArray:arrayR];
            //防止覆盖后面的数据
            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, statuses.count)];
            //刷新最新的数据，插入到最前面，防止覆盖后面的数据
            [self.filesArray insertObjects:statuses atIndexes:indexSet];
            
            
            [self.tableView reloadData];
            
            
            //        NSLog(@"res------%@",responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            NSLog(@"error----%@",error);
            [MBProgressHUD showError:@"服务器升级，请稍后再试"];
        }];
        
    }else{
        
        [self.tableView.mj_header endRefreshing];
    }

}


-(void)loadOldStatus
{
    NSUserDefaults *defaS = [NSUserDefaults standardUserDefaults];
    NSString *page = [defaS objectForKey:@"countSum"];
    pageS = [page intValue];
//    NSLog(@"pagesS%d",pageS);
    
    if (pageS%10 != 0) {
        n += 1;
//        NSLog(@"nnnn%d",n);
        
    }else{
        n+= 1;
    }
    if (n <= pages) {
        
        
        
        self.pageCount = [NSString stringWithFormat:@"%d",n];
       
        NSUserDefaults *phonede = [NSUserDefaults standardUserDefaults];
        NSString *phone = [phonede objectForKey:@"phonenum"];
        
        
        NSString *url = @"/app/queryRegistrationLog.do";
        NSString *path = [Hurl stringByAppendingString:url];
        AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"pageSize"]= self.pageCount;
        params[@"phone"]= phone;
      
        [mgr POST:path parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            
            [self.tableView.mj_footer endRefreshing];
            
            NSDictionary *info =(NSDictionary *)responseObject;
            NSMutableArray *arrayR = info[@"resultMap"][@"result"];
            NSArray *arr= (NSMutableArray *)[HJDFileModel mj_objectArrayWithKeyValuesArray:arrayR];
            
            [self.filesArray addObjectsFromArray:arr];
            
            
            [self.tableView reloadData];
            
            
                    NSLog(@"res------%@",responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            NSLog(@"error----%@",error);
            [MBProgressHUD showError:@"服务器升级，请稍后再试"];
        }];
    }else{
        
        [self.tableView.mj_footer endRefreshing];
        [MBProgressHUD showError:@"最后一页了"];
    }
  
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.filesArray.count;
   
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"Cell";
    HJDFileViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[HJDFileViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    HJDFileModel * model = self.filesArray[indexPath.row];
    
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    
    [inputFormatter setDateFormat:@"yyyy-MM-dd"];
    
    NSDate *inputDate = [inputFormatter dateFromString:model.createTime];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *comp = [[NSDateComponents alloc]init];
    NSInteger flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday |
    NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    
    comp = [calendar components:flags fromDate:inputDate];
    NSInteger month = [comp month];
    NSInteger day = [comp day];
    NSInteger year = [comp year];

    
    cell.dateLbl.text = [NSString stringWithFormat:@"%ld.%ld",month,day];
    cell.yearLbl.text = [NSString stringWithFormat:@"%ld",year];
    cell.nameLbl.text = @"检查医生：";
    cell.cnameLbl.text = model.name;
    cell.projectLbl.text = @"产检项目：";
    cell.cprojectLbl.text = model.items;
    cell.numLbl.text = @"产检次数：";
    NSUserDefaults *defa = [NSUserDefaults standardUserDefaults];
    NSString *str = [defa objectForKey:@"countSum"];

    cell.cnumLbl.text = [NSString stringWithFormat:@"%@次",str];
    cell.weekLbl.text = model.yunWeeks;
  


    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 200;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   HJDDateilsViewController *detail = [[HJDDateilsViewController alloc]init];
    
    detail.fileModel = self.filesArray[indexPath.row];
    [self.navigationController pushViewController:detail animated:YES];
}

@end
